<?php

namespace Admin\Controller;
use Think\Controller;
use Admin\Controller\AdminController;
/**
 * 菜单模块
 * 1.增加/修改套餐 增加了分页功能，对应Action-addCollocationPage，旧版本是addCollocation
 */

class OrderController extends AdminController{
	private $curPeriod;
	private $curFoodsNames;
    public function _initialize(){
        parent::_initialize();
        // 获取当前准备期或进行期的期数内容
        $condition = array();
        $condition['status'] = array(array('eq',C('p_status_ready')),array('eq',C('p_status_go')), 'or') ;
    	$this->curPeriod = M('period')->where($condition)->find();
    	
    	// 检查用户权限
    	$chkUsrPrilgRes = checkUserPrivilege();
		if($chkUsrPrilgRes[0]) {
			$this->error($chkUsrPrilgRes[1]);
		}
    }

    public function index(){
        $authority_model = M('wxuser_authority'); 
        $where = array('funcname'=>C('FUNC_NAME'),'isauth'=>0);
        $count = $authority_model->where($where)->count();
        $Page  = new \Think\Page($count,30);
        $show  = $Page->show();

        $res =  $authority_model->where($where)->order('applytime desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('res',$res);
        $this->assign('page',$show);
        
        $this->display(); 
    }
	
	//显示所有菜单 订单状态 1:未发货 2:已发货 3:已收货 0:全部订单
    public function showAll(){
        //$user_m = M("customer_user_v",'crm_cs_','db_config');
        // 处理查询不同订单类型
        $periodING = false;
        $periodName = '';
        $state = 0;
        $condition = array();
        
        if($this->curPeriod) {
			$period = $this->curPeriod['periodid'];
			$periodName = $this->curPeriod['pname'];
			$periodING = true;
		} else {
			// 查询出刚关闭的一期
			$condition_1['doGeneral'] = array('eq', 1);
			$condition_1['status'] = array('eq', 3);
			$lastPeriod = M('period')->where($condition_1)->order('endtime desc')->limit(1)->select();
	        $period = $lastPeriod[0]['periodid'];
	        $periodName = $lastPeriod[0]['pname'];
		}
        // 如果默认或者是当前订单
        if(I('state') == null || I('state') == 0) {
			$condition['a.opid'] = $period;
        } else {
        	$state = I('state');
	        $condition['a.opid'] = array('neq', $period);
        }
        
        $order_m = M("order"); 
        $count = count($order_m->alias('a')->join('__WXUSER__ as b ON b.BASKETID = a.BASKETID')->where($condition)->select());
        $Page  = new \Think\Page($count,10);
        $show  = $Page->show();

        $res = $order_m
        	->alias('a')
        	->join('__WXUSER__ as b ON b.BASKETID = a.BASKETID')
        	->where($condition)
        	->order('oid desc')
        	->limit($Page->firstRow.','.$Page->listRows)
        	->select();
        foreach($res as $key => $item) {
        	$foods = unserialize($item['ofoods']);
        	$item['ofoods'] = $foods;
	        $res[$key] = $item;
        }
        $this->assign('res',$res);
        $this->assign('page',$show);
        $this->assign('state', $state);
        $this->assign('periodING', $periodING);
        $this->assign('pname', $periodName);
        $this->display(); 
    }

    // 展示订单详情，并发货
    public function detailOrder(){
        if( IS_POST ){
            $order_m = M("order");
            
            $oid = I('oid');
            $postcode = I('opostcode');

            $condition = array('oid' => $oid);
            $sendtime = time();
            $data = array('sendtime'=>$sendtime, 'postcode'=>$postcode, 'state'=>C('SENDED'));
            
            $res = $order_m->where($condition)->save($data);
            if($res){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }   
            
            // 加入模板消息，发货成功
            // 根据oid查询 客户信息，主要是openid
            $res =  $order_m->join('tp_wxuser ON tp_order.openid = tp_wxuser.openid')->where($condition)->select();
            $openid = $res[0]['openid'];
            $foodsTotal = count(unserialize($res[0]['ofoods']));
            
            $deliTimeSec = $sendtime + (24*3600);
            $deliTime = date("Y-m-d", $deliTimeSec);
            $data = array("touser"=>"$openid",
						"template_id"=>"7E9CtvFUwMJyP_QkudlGiaPWZaLatwkVShnvDY3PdZc",
						"url"=> C('site_url').'/'.U('Wap/OrderFood/myOrder'),
						"topcolor"=>"#FF0000",
						"data"=> array("first" =>array("value"=>"本期九亩公社点菜订单已送出", "color"=>"#173177"), 
									"keyword1" =>array("value"=>"配送中", "color"=>"#173177"),
									"keyword2" =>array("value"=>"圆通快递", "color"=>"#173177"),
									"keyword3" =>array("value"=>"$oid", "color"=>"#173177"),
									"keyword4" =>array("value"=>"$deliTime", "color"=>"#173177"),
									"keyword5" =>array("value"=>"一共".$foodsTotal."份，将尽快送达！", "color"=>"#173177"),
									"remark"   =>array("value"=>"为保留营养，请第一时间烹制。", "color"=>"#173177"),
						)
			);
			$weObj = new \Org\Util\Wechat();
			$msg_result = $weObj->sendTemplateMessage($data);
        } else {
            $oid = I('oid');
            $order_m = M("order");
            $where = array('oid'=>$oid);
            $res = $order_m->where($where)->find();
            $foods = unserialize($res['ofoods']);
            $mark = empty($res['mark']) ? '空' : $res['mark'];

            $this->assign('foods',$foods);
            $this->assign('mark', $mark);
            $this->assign('oid', $oid);
            $this->assign('postcode', $res['postcode']);
            $this->assign('sendtime', $res['sendtime']);
            
            $this->display();
        }
    }

	public function editAutoOrder() {
		if(IS_POST) {
			$orderid = trim(I('orderid'));
			$openid = I('openid');
			$foods = I('foods');
			$orderFoods = array();
			foreach($foods as $key => $food) {
				if($food['isChs'] == 1) {
					array_splice($foods[$key], 0, 1);
					$orderFoods[$key] = $foods[$key];
				}
			}
			
			$ser_foods = serialize(array('colfood' => $orderFoods));
			
			$odata = array(
				'ofoods'	=> $ser_foods,
				'addtime'	=> time(),
			);
			$condition = array('oid' => $orderid);
			$res = M('order')->where($condition)->save($odata);
			
			if($res) {
				$this->success('修改成功');
			} else {
				$this->error('修改失败');
			}
		}else {
			$oid = I('oid');
			$orderInfo = M('order')->join('__WXUSER__ ON __ORDER__.OPENID = __WXUSER__.OPENID')->where(array('oid' => $oid))->find();
			if(!$orderInfo) {$this->error('此订单不存在!');}
			
			// 查询出刚关闭的一期
			$condition_1['doGeneral'] = array('eq', 1);
			$condition_1['status'] = array('eq', 3);
			$lastPeriod = M('period')->where($condition_1)->order('endtime desc')->limit(1)->select();
	        $period = $lastPeriod[0];
	        $periodid = $period['periodid'];
			
			// 获取到匹配套餐的菜品
			$condition['colname'] = $orderInfo['colid'];
			$period_collocation_m = M('period_collocation');
			$cbpFoods = $period_collocation_m->join('__PERIOD_COLLOCATION_ITEM__ ON __PERIOD_COLLOCATION__.PCOLID = __PERIOD_COLLOCATION_ITEM__.PC_COLID')->join('__FOOD__ ON __FOOD__.ID = __PERIOD_COLLOCATION_ITEM__.FOODID')->where($condition)->select();
			
			$this->assign('cbpFoods', $cbpFoods);
			
			$orderFoods = unserialize($orderInfo['ofoods']);
			
			$this->assign('orderFoods', $orderFoods);
			$this->assign("orderid", $oid);
			$this->assign("colname", $orderInfo['colid']);
			$this->assign("colCreditTotal", $cbpFoods[0]['colmoney']);
			// 表明当前有“准备”的期数
	    	$this->assign('curItem', $period);
			$this->display();
		}
	}

	/*
	 * 	管理员取消自动订单
	 */
	public function cancelManuOrder() {
		$oid = I('oid');
		$condition_0 = array("oid" => $oid);
		$res = M('order')->where($condition_0)->delete();
		if($res) {
			$this->success("删除成功");
		}else {
			$this->error("删除失败");
		}
	}

    public function delOrder() {
	    $oid = I('oid');
	    
	    $condition = array('oid' => $oid);
	    $order_m = M('order');
	    $res = $order_m->where($condition)->delete();
	    if($res) {
		    $this->success('删除成功');
	    } else {
		    $this->error('删除失败');
	    }
    }

    public function showSorts() { 
	    
	    $sort_m = M('food_sort');
        $count = count($sort_m->select());
        $Page  = new \Think\Page($count,30);
        $show  = $Page->show();
        $res =  $sort_m->order('`sort` ASC')->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $this->assign('sorts', $res);
        $this->assign('page', $show);
        
	    $this->display();
    }
    
    public function addSort() {
    	if(IS_POST) {
	    	$sid = I('sid');
	    	$name = I('sort_name');
	    	$des = I('sort_des');
	    	$sort = I('sort');
	    	$data = array('id' => $sid, 'name' => $name, 'des' => $des, 'sort' => $sort);
	    	if($sid != null) {
	    		$data = array('id' => $sid, 'name' => $name, 'des' => $des, 'sort' => $sort);
		    	$res = M('food_sort')->where(array('id' => $sid))->save($data);
	    	} else {
	    		$data = array('name' => $name, 'des' => $des, 'sort' => $sort);
		    	$res = M('food_sort')->add($data);
	    	}
	    	
	    	if($res){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            } 
    	} else {
		    $sid = I('sid');
		    if($sid != null) {
			    $sort = M('food_sort')->where(array('id' => $sid))->find();
		    }
		    $this->assign('sort', $sort);

		    $this->display();
	    }
    }
    
    public function delSort() {
	    $id = I('sid');
	    
	    $res1 = M('food_sort')->where(array('id' => $id))->delete();
	    // 删除所有此类下的菜品
	    $res2 = M('food')->where(array('sid' => $id))->delete();
	    
	    if($res1){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        } 
    }

    public function showFoods() {
	   	import("ORG.Util.Page"); 
	   	
        $food_m = M("food");
        $count = count($food_m->select());
        $Page  = new \Think\Page($count,10);
        $show  = $Page->show();
        $foods =  $food_m->order('`sort` ASC')->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $sorts = M('food_sort')->select();
        $new_sorts = array();
        
        foreach($sorts as $sort) {
	        $new_sorts[$sort['id']] = $sort['name'];
        }
        
        $this->assign('foods', $foods);
        $this->assign('page',$show);
        $this->assign('sorts', $new_sorts);
        
        $this->display();
    }

    public function addFood() {
    	if(IS_POST) {
	    	$id = I('id');
	    	$name = I('name');
	    	$sid = I('sid');
	    	$price = I('price');
	    	$image = I('image');
	    	$unit = I('unit');
	    	$sort = I('sort');
	    	$des = I('des');
	    	$instock = I('instock');
	    	
	    	$data = array();
	    	$data['sid'] = $sid;
		    $data['name'] = $name;
		    $data['price'] = $price;
		    $data['image'] = $image;
		    $data['unit'] = $unit;
		    $data['instock'] = $instock;
		    $data['sort'] = $sort;
		    $data['des'] = $des;
		    $data['creattime'] = time();
		    
		    $res = null;
		    $res1 = null;
		    $res2 = null;
	    	if(empty($id)) {
		    	$res1 = M('food')->add($data);
		    	// 更新此类菜品分类的菜品书
		    	$sort = M('food_sort')->where(array('id' => $sid))->find();
		    	$num = $sort['num'] + 1;
		    	$sort_data = array('num' => $num);
		    	
		    	$res2 = M('food_sort')->where(array('id' => $sid))->save($sort_data);
	    	} else {
		    	$res = M('food')->where(array('id'=>$id))->save($data);
	    	}
	    	
	    	if($res || ($res1 && $res2)){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            } 
    	} else {
    		// 如果有 菜品id
    		$food = array();
    		$fid = I('id');
    		if(!empty($fid)) {
	    		$food = M('food')->where(array('id'=>$fid))->find();
	    		$this->assign('sid', $food['sid']);
    		}
		    $sorts = M('food_sort')->select();
	        $new_sorts = array();
	        
	        foreach($sorts as $sort) {
		        $new_sorts[$sort['id']] = $sort['name'];
	        }
	        
	        $this->assign('sorts', $new_sorts);
	        $this->assign('food', $food);
	        $this->assign('test', 9);
	        
		    $this->display();
	    }
    }

    public function delFood() {
	    $id = I('id');
	    $res = M('food')->where(array('id' => $id))->delete();
	    
	    if($res){
		    $this->success('修改成功');
		}else{
			$this->error('修改失败');
		} 
    }

    //审核用户
    public function passCheck(){
        if( IS_POST ){
            $user_m = M("user",'crm_cs_','db_config');
            
            $openid 	= I('post.openid');
            $nickname 	= I('post.nickname');
            $truename 	= I('post.truename');
            $phone 		= I('post.phone');
            $mail 		= I('post.mail');
            $customer 	= I('post.customer');
            if($truename == '' || $phone == '' || $mail == '' || $customer == '' ) {
                $this->error('请完整填写审核资料');
            }
            $arr = array('openid' =>$openid ,'nick_name' =>$nickname,'true_name'=>$truename,'phone'=>$phone,'mail'=>$mail,'customer_id'=>$customer,'status'=>1,'create_time'=>date("Y-m-d H:i:s", time()) );
            
            $res = $user_m->add($arr);
            if($res){
                $authority_model = M('wxuser_authority');
                $authority_model->where(array('openid' =>$openid ))->save(array('isauth' =>1 ));//测试1－>0
                $this->success('审核成功');
            }else{
                $this->error('审核失败');
            }            
        } else {//显示审核内容
            $openid = I('get.openid');
            $authority_model = M('wxuser_authority');
            $where = array('openid'=>$openid);
            $res = $authority_model->where($where)->find();
            $this->assign('user',$res);

            $customer_model = M("customer",'crm_cs_','db_config');
            $customer_res = $customer_model->select();
            $this->assign('customer_list',$customer_res);

            $this->display();
        }

    }

    // 展示套餐列表
    public function showCombopack() {
	    import("ORG.Util.Page"); 
	   	/*
	   	$state = I('state');
	   	if(empty($state)) {
		   	$state = 1;	// 进行中的套餐
	   	}
	   	
	   	if(!$this->curPeriod) {
		   	$this->error('当前没有进行中的期数, 请前往期数管理进行操作!');
	   	}*/
	   	// 查询出当前套餐的内容
        $combopack_m = M("combopack");
        $count = count($combopack_m->select());
        $Page  = new \Think\Page($count,10);
        $show  = $Page->show();
        $condition = array();
        
        $cmbpacks =  $combopack_m->where($condition)->order('`cpname` ASC')->limit($Page->firstRow.','.$Page->listRows)->select();
    
        $this->assign('cmbpacks', $cmbpacks);
        $this->assign('page',$show);
        $this->assign('state',1);
        $this->display();
    }

    public function addCombopack() {
    	$cpid = I('cpid');
	    if(IS_POST) {
		    $cp_collocation = I('cp_collocation');
		    $collocations = explode(',', $cp_collocation);
		    
		    $data = array();
		    $data['cpname'] = I('cpname');
		    $data['cp_collocation'] = json_encode($collocations);
		    $data['createtime']	= time();
		    $res = null;
		    if(!empty($cpid)) {
			    $res = M('combopack')->where(array('id' => $cpid))->save($data);
		    } else {
			    $res = M('combopack')->add($data);
		    }
		    
		    if($res) {
			    $this->success('添加成功');
		    } else {
			    $this->error('添加失败');
		    }
	    } else {
	    	$condition = array();
	        if(!empty($cpid)) {
		        $condition['id'] = $cpid;
		        $combopack = M('combopack')->where($condition)->find();
		        $combopack['cp_collocation'] = json_decode($combopack['cp_collocation']);
		        $this->assign('combopack', $combopack);
	        }
	        
		    $this->display();
	    }
    }

    // 展示套餐列表
    public function showCollocation() {
	    import("ORG.Util.Page"); 
	   	// 查询出当前套餐的内容
        $collocation_m = M("period_collocation");
        $count = count($collocation_m->where($condition)->select());
        $Page  = new \Think\Page($count,10);
        $show  = $Page->show();
        
        $collocations = $collocation_m->where($condition)->order('`colname` ASC')->limit($Page->firstRow.','.$Page->listRows)->select();
        
        foreach($collocations as $k => $collocation) {
	        $colid = $collocation['pcolid'];
	        $collocation_items = M('period_collocation_item')->where(array('pc_colid' => $colid))->select();
	        $collocations[$k]['collocation_items'] = $collocation_items;
        }
        
        $this->assign('collocations', $collocations);
        $this->assign('page',$show);
        
	   	$this->display();
    }

	public function showColFood() {
		$pcolid = I("cid");
		
		import("ORG.Util.Page");
		
		$col_item_m = M("period_collocation_item");
		$condition_0 = array("pc_colid" => $pcolid);
		$count = count($col_item_m->where($condition_0)->select());
		$Page = new \Think\Page($count, 5);
		$show = $Page->show();
		
		$colFoods = $col_item_m->where($condition_0)->limit($Page->firstRow.','.$Page->listRows)->select();
		
		$this->assign('cid', $pcolid);
		$this->assign('colFoods', $colFoods);
		$this->assign('page', $show);
		
		$this->display();
	}

	public function addColFood() {
		$colid = I("get.cid");
		$condition_0 = array("pcolid" => $colid);
		$col = M("period_collocation")->where($condition_0)->find();
		$this->assign("col", $col);
		$this->assign("cid", $colid);
		
		if(IS_POST) {
			// 如果keyword是通过POST过来，即form提交过来
			$keyword = I('post.keyword');
			$colFoods = $this->searchColFoods($keyword, $colid);
			$this->assign("colFoods", $colFoods);
			$this->assign("keyword", $keyword);
			
			$this->display();
		} else {
			// 如果keyword是通过GET过来，即分页链接
			$keyword = I('get.keyword');
			if(!empty($keyword)) {
				$colFoods = $this->searchColFoods($keyword, $colid);
				$this->assign('colFoods', $colFoods);
			}
			$this->display();
		}
	}

	public function delColFood() {
		$itemid = I('id');
		
		$condition_0 = array("id" => $itemid);
		$res = M("period_collocation_item")->where($condition_0)->delete();
		if($res) {
			$this->success("删除成功");
		} else {
			$this->error("删除失败");
		}
	}
	
	public function del_food2col() {
		$colid = I('get.colid');
		$foodid = I('post.foodid');
		
		$condition_0 = array("pc_colid" => $colid, "foodid" => $foodid);
		$res = M("period_collocation_item")->where($condition_0)->delete();
		if($res) {
			$result['result'] = "从套餐中删除成功";
			$result['code'] = 1;
		} else {
			$result['result'] = "从套餐中删除失败";
			$result['code'] = 0;
		}
		
		$this->ajaxReturn($result);
	}
	
	public function add_food2col() {
		$colid = I('get.colid');
		$data = $_POST;
		$data['pc_colid'] = $colid;
		$data['createtime'] = time();
		$res = M("period_collocation_item")->add($data);
		if($res !== false) {
			$result['result'] = "加入套餐成功";
		} else {
			$result['result'] = "加入套餐失败";
		}
		$this->ajaxReturn($result);
	}
	
	// 将菜品编入某一个分组中
	public function editFGroup() {
		$id = I('id');
		$fgid = I('fgid');
		$ginstock = I('ginstock');
		
		$res = M('period_collocation_item')->where("`id` = '$id'")->save(array('fgroup' => $fgid, 'ginstock' => $ginstock));
		$res = $res ? 1 : 0;
		return $this->ajaxReturn($res);
	}
	
	private function searchColFoods($keyword, $colid) {
		import("ORG.Util.Page");
		$condition_0 = array();
		if(!empty($keyword)) {
			$condition_0['a.name'] = array('like', "%$keyword%");
		}
		
		$model = M();
		$subQuery = $model->table("tp_period_collocation_item")->where(array("pc_colid" => $colid))->select(false);
		
		$count = M("food")
		->alias('a')
		->join("LEFT JOIN (".$subQuery.") c ON a.id = c.foodid")
		->where($condition_0)
		->count();
		$Page = new \Think\Page($count, 5);
		
		$colFoods = M("food")
		->alias('a')
		->join("LEFT JOIN (" . $subQuery . ") c ON a.id = c.foodid")
		->where($condition_0)
		->limit($Page->firstRow.','.$Page->listRows)
		->order('a.creattime desc')
		->getField('a.id as foodid, a.name as foodname, c.pc_colid as pc_colid, c.reqchoose as reqchoose, c.defchoose as defchoose, c.price as price, c.orignum as orignum, a.creattime as createtime');
		
		$show = $Page->show();
		$this->assign("Page", $show);
		
		return $colFoods;
	}
    
    public function detailCollocation() {
	    $cid = I('cid');
	    $condition_1 = array('pc_colid' => $cid);
		$cFoods = M('period_collocation_item')->join('__PERIOD_COLLOCATION__ ON __PERIOD_COLLOCATION_ITEM__.PC_COLID = __PERIOD_COLLOCATION__.PCOLID')->where($condition_1)->select();
		
		$this->assign('cfoods', $cFoods);
		
		$this->display();
    }
    
    public function getOneCollocations() {
	    $combopackid = I('combopackid');
	    $combopack = M('combopack')->where(array('cpid' => $combopackid))->find();
	    $this->ajaxReturn($combopack['cp_collocation']);
    }
    
    /* 新增 备选 */
    public function showOption() {
    	import("ORG.Util.Page"); 
	   	// 查询出当前套餐的内容
        $option_m = M("period_option_item");
		$option_items = $option_m->join('__FOOD__ ON __PERIOD_OPTION_ITEM__.FOODID = __FOOD__.ID')->getField('tp_period_option_item.foodid as foodid, tp_period_option_item.foodname as fname, tp_food.instock as stock');
		$options = array($option_items);
        $this->assign('options', $options);
        
	   	$this->display();
    }
    
    /* 同步套餐菜品 */
    public function asyncColFood() {
    	$p_col_info = M('period_collocation')->where("`colname` = 'A'")->find();
    	$p_colid = $p_col_info['pcolid'];

    	$where = array();
    	$where['foodname'] = array('not in', C('except_option_to_del_food'));
    	M('period_option_item')->where($where)->delete();
    	$colFoods = M('period_collocation_item')->where("`pc_colid` = '$p_colid'")->select();
    	$data_opt_food = array();
    	foreach ($colFoods as $key => $food) {
   			 $data_opt_food[] = array(
   			 	'foodid'	=> $food['foodid'],
   			 	'foodname'	=> $food['foodname'],
   			 	'createtime'=> time(),
   			 );
       	}
       	$res = M('period_option_item')->addAll($data_opt_food);
       	if($res) {
       		$this->success('同步套餐菜品成功');
       	} else {
       		$this->error('同步套餐菜品失败');
       	}
    }

    public function showOptionFood() {
		import("ORG.Util.Page");
		
		$opt_item_m = M("period_option_item");
		$count = count($opt_item_m->select());
		$Page = new \Think\Page($count, 5);
		$show = $Page->show();
		$optFoods = $opt_item_m
		->join("__FOOD__ ON __PERIOD_OPTION_ITEM__.FOODID = __FOOD__.ID")
		->limit($Page->firstRow.','.$Page->listRows)
		->getField('tp_period_option_item.foodid as foodid, tp_period_option_item.foodname as foodname, tp_food.instock as instock, tp_period_option_item.id as id, tp_period_option_item.limit_num as limit_num');
		
		$this->assign('optFoods', $optFoods);
		$this->assign('page', $show);
		
		$this->display();
	}
    
    public function delOptionFood() {
		$itemid = I('id');
		
		$condition_0 = array("id" => $itemid);
		$res = M("period_option_item")->where($condition_0)->delete();
		if($res) {
			$this->success("删除成功");
		} else {
			$this->error("删除失败");
		}
	}
    
    public function addOptionFood() {
	    // 查找出备选菜品
	    $optFoods = M("period_option_item")->getField('foodid, foodname');
	    $this->assign("optFoods", $optFoods);
	    
		if(IS_POST) {
			// 如果keyword是通过POST过来，即form提交过来
			$keyword = I('post.keyword');
			$schFoods = $this->searchOptOrPlusFoods($keyword);
			$this->assign("schFoods", $schFoods);
			$this->assign("keyword", $keyword);
			$this->display();
		} else {
			// 如果keyword是通过GET过来，即分页链接
			$keyword = I('get.keyword');
			if(!empty($keyword)) {
				$schFoods = $this->searchOptOrPlusFoods($keyword);
				$this->assign('schFoods', $schFoods);
			}
			$this->display();
		}
    }
    
    private function searchOptOrPlusFoods($keyword) {
		import("ORG.Util.Page");
		$condition_0 = array();
		if(!empty($keyword)) {
			$condition_0['name'] = array('like', "%$keyword%");
		}
		
		$count = M("food")
		->where($condition_0)
		->count();
		$Page = new \Think\Page($count, 5);
		
		$schFoods = M("food")
		->where($condition_0)
		->limit($Page->firstRow.','.$Page->listRows)
		->order('creattime desc')
		->getField('id as foodid, name as foodname, instock as instock, creattime as createtime');
		
		$show = $Page->show();
		$this->assign("Page", $show);
		
		return $schFoods;
	}
    
    public function del_food2opt() {
		$foodid = I('post.foodid');
		
		$condition_0 = array("foodid" => $foodid);
		$res = M("period_option_item")->where($condition_0)->delete();
		if($res) {
			$result['result'] = "从套餐中删除成功";
			$result['code'] = 1;
		} else {
			$result['result'] = "从套餐中删除失败";
			$result['code'] = 0;
		}
		
		$this->ajaxReturn($result);
	}
	
	public function add_food2opt() {
		$data = $_POST;
		$data['createtime'] = time();
		$res = M("period_option_item")->add($data);
		
		$condition_0 = array("id" => $data['foodid']);
		$res1 = M("food")->where($condition_0)->save( array("instock" => $data['instock']));
		if($res !== false && $res1 !== false) {
			$result['result'] = "加入套餐成功";
		} else {
			$result['result'] = "加入套餐失败";
		}
		$this->ajaxReturn($result);
	}
    /* 结束 新增 备选 */
    
    /* 开始 新增 另购 */
    public function showPlus() {
	   	// 查询出当前套餐的内容
        $plus_m = M("period_plus_item");
		$plus_items = $plus_m->join('__FOOD__ ON __PERIOD_PLUS_ITEM__.FOODID = __FOOD__.ID')->getField('tp_period_plus_item.foodid as foodid, tp_period_plus_item.foodname as fname, tp_food.instock as stock');
		$pluss = array($plus_items);
        $this->assign('pluss', $pluss);
        
	   	$this->display();
    }
    
    public function showPlusFood() {
		import("ORG.Util.Page");
		
		$opt_item_m = M("period_plus_item");
		$count = count($opt_item_m->select());
		$Page = new \Think\Page($count, 5);
		$show = $Page->show();
		$plusFoods = $opt_item_m
		->join("__FOOD__ ON __PERIOD_PLUS_ITEM__.FOODID = __FOOD__.ID")
		->limit($Page->firstRow.','.$Page->listRows)
		->getField('tp_period_plus_item.foodid as foodid, tp_period_plus_item.foodname as foodname, tp_food.instock as instock, tp_period_plus_item.id as id');
		
		$this->assign('plusFoods', $plusFoods);
		$this->assign('page', $show);
		
		$this->display();
	}
    
    public function delPlusFood() {
		$itemid = I('id');
		
		$condition_0 = array("id" => $itemid);
		$res = M("period_plus_item")->where($condition_0)->delete();
		if($res) {
			$this->success("删除成功");
		} else {
			$this->error("删除失败");
		}
	}
	
	public function addPlusFood() {
	    // 查找出另购菜品
	    $plusFoods = M("period_plus_item")->getField('foodid, foodname');
	    $this->assign("plusFoods", $plusFoods);
	    
		if(IS_POST) {
			// 如果keyword是通过POST过来，即form提交过来
			$keyword = I('post.keyword');
			$schFoods = $this->searchOptOrPlusFoods($keyword);
			$this->assign("schFoods", $schFoods);
			$this->assign("keyword", $keyword);
			$this->display();
		} else {
			// 如果keyword是通过GET过来，即分页链接
			$keyword = I('get.keyword');
			if(!empty($keyword)) {
				$schFoods = $this->searchOptOrPlusFoods($keyword);
				$this->assign('schFoods', $schFoods);
			}
			$this->display();
		}
    }
    
    public function del_food2plus() {
		$foodid = I('post.foodid');
		
		$condition_0 = array("foodid" => $foodid);
		$res = M("period_plus_item")->where($condition_0)->delete();
		if($res) {
			$result['result'] = "从套餐中删除成功";
			$result['code'] = 1;
		} else {
			$result['result'] = "从套餐中删除失败";
			$result['code'] = 0;
		}
		
		$this->ajaxReturn($result);
	}
	
	public function add_food2plus() {
		$data = $_POST;
		$data['createtime'] = time();
		$res = M("period_plus_item")->add($data);
		
		$condition_0 = array("id" => $data['foodid']);
		$res1 = M("food")->where($condition_0)->save( array("instock" => $data['instock']));
		if($res !== false && $res1 !== false) {
			$result['result'] = "加入套餐成功";
		} else {
			$result['result'] = "加入套餐失败";
		}
		$this->ajaxReturn($result);
	}
    /* 结束 新增 另购 */
    
    public function showPeriods() {
	    import("ORG.Util.Page"); 
        $period_m = M("period");
        $count = count($period_m->select());
        $Page  = new \Think\Page($count,10);
        $show  = $Page->show();
        $periods =  $period_m->order('`pname` DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        // 判断是否当前有期数处在 准备 | 进行 状态
        if($this->curPeriod) {
	    	$this->assign('using', true);
    	} else {
	    	$this->assign('using', false);
    	}
        $this->assign('periods', $periods);
        $this->assign('page',$show);
        $this->assign('state',0);
        
        //	获取到当前配菜信息:用户组 菜品信息 起止时间
        $cur_group = M('group')->where("`is_use` = 1")->find();
        $this->assign('cur_group', $cur_group);
        
        $condition['colname'] = 'A';
		$period_collocation_m = M('period_collocation');
		$cbpFoods = $period_collocation_m->join('__PERIOD_COLLOCATION_ITEM__ ON __PERIOD_COLLOCATION__.PCOLID = __PERIOD_COLLOCATION_ITEM__.PC_COLID')->join('__FOOD__ ON __FOOD__.ID = __PERIOD_COLLOCATION_ITEM__.FOODID')->where($condition)->select();
		$cbpfoods_str = '';
		foreach($cbpFoods as $food) {
			$cbpfoods_str .= $food['foodname'] . ' ';
		}
		$this->assign('cbpfoods_str', $cbpfoods_str);
		
		$opFoodsList = M('period_option_item')->join('__FOOD__ ON __PERIOD_OPTION_ITEM__.FOODID = __FOOD__.ID')->field('tp_period_option_item.id as id, tp_period_option_item.foodid as foodid, tp_food.sid as sid, tp_period_option_item.foodname as foodname, tp_food.price as price, tp_food.instock as instock, tp_food.image as image, 0 as orignum')->select();
		\Think\Log::write("当前备选的菜品:" . dump($opFoodsList, false));
		
		$opfoods_str = '';
		foreach($opFoodsList as $food) {
			$opfoods_str .= $food['foodname'] . ' ';
		}
		$this->assign('opfoods_str', $opfoods_str);
		
        $this->display();
    }
    
    /*
     * 期数有4种状态: 0 未开启 | 1 开启 | 2 进行 | 3 关闭, 查看Admin的config
     */
    public function addPeriod() {
	    if(IS_POST) {
		    $id = I('periodid');
		    $fromtime = I('fromtime');
		    $endtime = I('endtime');
		    
		    // id为空即 新增
		    $data = array();
		    // 转成秒数
		    $data['fromtime'] = strtotime($fromtime);
		    $data['endtime'] = strtotime($endtime);
		    $data['ppname'] = I('ppname');
		    if(empty($id)) {    
		    	$data['pname'] = I('pname');
		    	$res = M('period')->add($data);
		    	if(!$res) {
			    	$this->error('新增失败, 请重新配置期数!');
			    	exit;
		    	} else {
			    	$this->success('新增成功!');
			    	exit;
		    	}
		    } else {
			    $res = M('period')->where(array('periodid' => $id))->save($data);
			    if($res) {
				    $this->success('新增成功!');
			    	exit;
			    } else {
				    $this->error('修改失败, 请重新配置期数!');
				    exit;
			    }
		    }
	    } else {
	    	$id = I('periodid');
	    	// 如果有期数id，即修改
	    	$period = null;
	    	if(!empty($id)) {
		    	$period = M('period')->where(array('periodid' => $id))->find();
		    	if(!empty($period)) {
			    	$period['fromtime'] = date("Y-m-d H:i:s", $period['fromtime']);
			    	$period['endtime'] = date("Y-m-d H:i:s", $period['endtime']);
		    	}
	    	}
	    	$this->assign('period', $period);
	    	
		    $this->display();
	    }
    }
    
    /*
     * 准备一期
     * 查看是否存在 open
     * 判断是否比上一期晚，是否是剩下的期数最早的（Todo...）
     */
    public function readyPeriod() {
		$id = I('periodid');
		$result = array();
		if(empty($id)) {
			$result['result'] = '参数错误, 请检查!';
			$result['code'] = 0;
		}
		$condition = array();
	   	$condition['status'] = array('in', array(C('p_status_go'), C('p_status_ready')));
	   	$goOrOpenItem = M('period')->where($condition)->select();
	   	if($goOrOpenItem) {
		   	$result['result'] = '当前存在进行中或准备的期数, 请先处理!';
		   	$result['code'] = 0;
	   	}
	   	
	   	$pitem = M('period')->where(array('periodid' => $id))->find();
	   	// To do...
	   	if($pitem['status'] != C('p_status_unopen')) {
		   	$result['result'] = '此期已开始或已关闭, 请检查!';
		   	$result['code'] = 0;
	   	}
	   	$data = array('status' => C('p_status_ready'));
	   	$res = M('period')->where(array('periodid' => $id))->save($data);
	   	
	   	if($res) {
		   	$result['result'] = '这期准备成功, 请前往去配置这期套餐信息!';
		   	$result['code'] = 1;
	   	} else {
		   	$result['result'] = '数据有错, 请返回检查!';
		   	$result['code'] = 0;
	   	}
	   	
	   	$this->ajaxReturn($result);
    }
    
    /*
     * 这个方法用于crontab中每分钟定时执行
     */
    public function openPeriod() {
	   	$ispush = true;
	   	$id = I('periodid');
	   	\Think\Log::write("期数id =>" . $id);
	   	$result = array();
	   	if(empty($id)) {
		   	$result['result'] = '参数错误, 请检查!';
		   	$result['code'] = 0;
		   	$ispush = false;
	   	}
	   	// 判断是否存在已经进行中的期数
	   	$goItem = M('period')->where(array('status' => C('p_status_go')))->find();
	   	if($goItem) {
		   	$result['result'] = '当前存在进行中的期数, 请等待上期结束再开启!';
		   	$result['code'] = 0;
		   	$ispush = false;
	   	}
	   	$pitem = M('period')->where(array('periodid' => $id))->find();
	   	if($pitem['status'] != C('p_status_ready')) {
		   	$result['result'] = '此期并不在准备阶段, 请检查!';
		   	$result['code'] = 0;
		   	$ispush = false;
	   	}
	   	
	   	// 检查是否套餐配齐了7个蔬菜
	   	$col_name = C('collocation_name');	// A
	   	$collocation = M('period_collocation')->where("`colname` = '$col_name'")->find();
	   	$col_id = $collocation['pcolid'];
	   	$foodsNums = M('period_collocation_item')
	   		->where("`pc_colid` = '$col_id'")
	   		->count();
	   	if($foodsNums < 7) {
		   	$result['result'] = '当前配置套餐菜品数量有误，小于7个，请检查!';
		   	$result['code'] = 0;
		   	$ispush = false;
		   	
		}
		
		if($ispush) {
			// Todo 群发消息
			$data = array('status' => C('p_status_go'));
			$res = M('period')->where(array('periodid' => $id))->save($data);
			if($res) {
				// 执行系统命令，让python往crontab里写任务
				$mod_name = C('MODULE_NAME');
				// exec方法不输出结果，因此不影响json返回
				// ob开头几个函数用于清空echo的缓冲区，因为system函数执行会输出结果
				ob_start();
				$py_result = system("python /www/web/9mu/public_html/".$mod_name."/addPeriodMissionToCrontab.py " . $mod_name);
				if($py_result == '3job-error') {
					ob_clean();
					ob_end_flush();
					$result['result'] = '3任务写入自动任务队列出错';
					$result['code'] = 0;
				} else {
					ob_clean();
					ob_end_flush();
					$result['result'] = '这期已经开启, 已向用户群发消息!';
					$result['code'] = 1;
				}
			} else {
				$result['result'] = '数据有错, 请返回检查!';
				$result['code'] = 0;
			}
		}
		$this->ajaxReturn($result);
		exit;
    }
    
    /*
     * 这个方法用于crontab中每分钟定时执行
     */
    public function closePeriod() {
    	// 找出正在进行的期数，检查时间是否已到，已到截止时间，停止
    	$condition = array('status' => C('p_status_go'));
	    $items = M('period')->where($condition)->select();
	    
	    if($items && count($items) > 1) {
		    \Think\Log::write('当前进行中的期数存在错误：存在两条同时进行的期数！');
		    exit;
	    }
	    
	    $closePid = $items['periodid'];
	    $data = array('status' => C('p_status_close'));
	    $res = M('period')->where(array('periodid' => $closePid))->save($data);
	    if($res) {
		    \Think\Log::write('期数(' . $items['pname'] . ')已关闭!');
	    } else {
		    \Think\Log::write('期数(' . $items['pname'] . ')关闭错误!');
	    }
    }
    
    public function curOrderList() {
	    import("Org.Util.PHPExcel");
	    import("Org.Util.PHPExcel.Writer.Excel5");
	    import("Org.Util.PHPExcel.IOFactory");
	    
	    $rand = rand(10,100);
	    $date = date("Y-m-d H:i:s", time());
	    $fileName = "{$date}_$rand.xls";
	    
	    // 设置PHPExcel对象，注意不能少了\
	    $objPHPExcel = new \PHPExcel();
	    $objProps = $objPHPExcel->getProperties();
	    
	    
	    if($this->curPeriod) {
			$period = $this->curPeriod['periodid'];
		} else {
			// 查询出刚关闭的一期
			$condition_1['doGeneral'] = array('eq', 1);
			$condition_1['status'] = array('eq', 3);
			$lastPeriod = M('period')->where($condition_1)->order('endtime desc')->select();
	        $period = $lastPeriod[0]['periodid'];
		}
	    
	    $condition_1 = array('tp_order.opid' => $period);
	    //$orderList = M('order')->field('tp_order.oid as id, tp_wxuser.truename as truename, tp_order.autoOrder as autoorder, tp_wxuser.basketid as basketid, tp_order.mark as mark, tp_order.ofoods as foods')->join('__WXUSER__ ON __ORDER__.BASKETID = __WXUSER__.BASKETID')->where($condition_1)->order('tp_wxuser.basketid ASC')->select();
	    $orderList = M('order')
	    	->join('__WXUSER__ ON __ORDER__.BASKETID = __WXUSER__.BASKETID')->where($condition_1)->order('tp_wxuser.basketid ASC')
	    	->getField('tp_wxuser.basketid as basketid, tp_wxuser.truename as truename, tp_order.autoOrder as autoorder,  tp_order.mark as mark, tp_wxuser.discount_money as discount_money, tp_order.ofoods as foods');
	    /*$data = array(
	    	array('id' => '123', 'name' => '王小二', 'tel' => '12323424'),
	    	array('id' => '345', 'name' => '李三', 'tel' => '434242'),
	    	array('id' => '456', 'name' => '张四', 'tel' => '34535'),
	    );*/
		// 获取当前订单出现过的菜品名
		$this->getCurFoodsNames($orderList);
		$curDate = date('m-d', time());
	    $headArr = array($curDate,'姓名', '订单类型', '备注','套餐金额');
	    $headArrLens = count($headArr);
	    
	    $headArr = array_merge($headArr, $this->curFoodsNames);
	    $curFoodsNamesLens = count($this->curFoodsNames);
	    
		foreach($orderList as $key => $list){
			$orderFoodsAndTotal = $this->getFoodInfo($list['foods']);
			$orderList[$key]['foods'] = $orderFoodsAndTotal['foods'];
		}
		// 对菜篮子号排序
		$newOrderList = $this->getSortedOrderList($orderList);
		
	    // 设置表头
	    $key = ord("A");
	    foreach($headArr as $v){
		    $colum = chr($key);
		    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum.'1', $v);
		    $key +=1;
	    }
	    
	    $column = 2;
	    $objActSheet = $objPHPExcel->getActiveSheet();
	    
	    // 设置单元格宽度
	    $objActSheet->getColumnDimension('A')->setWidth(12);
	    $objActSheet->getColumnDimension('C')->setWidth(18);
	    $objActSheet->getColumnDimension('D')->setWidth(12);
	    $objActSheet->getColumnDimension('E')->setWidth(30);
	    $objActSheet->getColumnDimension('F')->setwidth(12);
	    foreach($newOrderList as $key => $rows) {
		    $span = ord("A");
		    foreach($rows as $keyName => $value) {
			    $j = chr($span);
			    if($keyName == 'basketid'){
				    $objActSheet->setCellValue($j.$column, $value);
				    // 设置单元样式
				    $curColumn = $objActSheet->getStyle("$j$column");
				    $curColumn->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
				    $span++;
				} elseif($keyName == 'autoorder') {
				    if($value == 0) {
					   	$tvalue = '手工订单'; 
				    } elseif($value == 1) {
					    $tvalue = '自动订单';
				    } elseif($value == 2) {
					 	$tvalue = '取消订单';   
				    }
				    $objActSheet->setCellValue($j.$column, $tvalue);
				    $span++;
			    } elseif($keyName == 'foods') {
					for($i=0;$i<count($value);$i++) {
						$foodName = $value[$i]['foodname'];
						$foodNum = $value[$i]['num'];
						$index = 0;
						foreach($this->curFoodsNames as $fname) {
							if($fname == $foodName) {
								$objActSheet->setCellValue(chr($span+$index).$column, $foodName.'*'.$foodNum);
							}else {
								$index++;
							}
						}
					}
			    } else {
					$objActSheet->setCellValue($j.$column, $value);
					$span++;
			    }
			    
		    }
		    $column++;
	    }
	    
	    /* ------------ */
	    // 对相关单元格进行合并 | 统计 等操作
	    //$objActSheet->mergeCells('B2:B3');
	    /* ------------ */
	    $fileName = iconv("utf-8", "gb2312", $fileName);
	    
	    $objPHPExcel->setActiveSheetIndex(0);
	    ob_end_clean();
	    header('Content-Type: application/vnd.ms-excel');
	    header("Content-Disposition: attachment;filename=\"$fileName\"");
	    header('Cache-Control: max-age=0');
	    
	    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	    $objWriter->save('php://output');
	    exit;
    }
    
    // 导出配送单 配送人员用
    public function curOrderDeliverList() {
	    import("Org.Util.PHPExcel");
	    import("Org.Util.PHPExcel.Writer.Excel5");
	    import("Org.Util.PHPExcel.IOFactory");
	    
	    $rand = rand(10,100);
	    $date = date("Y-m-d H:i:s", time());
	    $fileName = "{$date}_$rand.xls";
	    
	    // 设置PHPExcel对象，注意不能少了\
	    $objPHPExcel = new \PHPExcel();
	    $objProps = $objPHPExcel->getProperties();
	    
	    if($this->curPeriod) {
			$period = $this->curPeriod['periodid'];
		} else {
			// 查询出刚关闭的一期
			$condition_1['doGeneral'] = array('eq', 1);
			$condition_1['status'] = array('eq', 3);
			$lastPeriod = M('period')->where($condition_1)->order('endtime desc')->select();
	        $period = $lastPeriod[0]['periodid'];
		}
	    
	    $condition_1 = array('tp_order.opid' => $period);
	    $orderList = M('order')
	    	->join('__WXUSER__ ON __ORDER__.BASKETID = __WXUSER__.BASKETID')->where($condition_1)->order('tp_wxuser.basketid ASC')
	    	->getField('tp_wxuser.basketid as basketid,tp_order.autoOrder as autoorder, tp_wxuser.truename as truename, tp_wxuser.discount_money as discount_money, tp_wxuser.address as address, tp_wxuser.tell as tell, tp_order.mark as mark, tp_order.ofoods as foods');
	    	
	    $this->getCurFoodsNames($orderList);
		
		// headArr 这里的字段与orderList中的字段要一一对齐
		$curDate = date('m-d', time());
		// 指定鸡蛋、土鸡到D E两列
	    $headArr = array($curDate,'订单类型','姓名', '鸡蛋', '土鸡', '额外消费','套餐金额', '地址', '电话', '点菜备注');
	    $headArrLens = count($headArr);
	    
	    //	将curFoodsNames中的鸡蛋 土鸡去掉
	    $chickenAndEggArr = C('xls_new_sort');
	    foreach($this->curFoodsNames as $fname) {
		    foreach($chickenAndEggArr as $key => $val) {
			    if($fname == $key) {
				    array_shift($this->curFoodsNames);
			    }
		    }
	    }
	    
	    $headArr = array_merge($headArr, $this->curFoodsNames);
	    $curFoodsNamesLens = count($this->curFoodsNames);
	    
	    /*$data = array(
	    	array('id' => '123', 'name' => '王小二', 'tel' => '12323424'),
	    	array('id' => '345', 'name' => '李三', 'tel' => '434242'),
	    	array('id' => '456', 'name' => '张四', 'tel' => '34535'),
	    );*/
		foreach($orderList as $key => $list){
			$orderFoodsAndTotal = $this->getFoodInfo($list['foods']);
			$address 	= $list['address'];
			$tell		= $list['tell'];
			$mark		= $list['mark'];
			$dis_money	= $list['discount_money'];
			// 为了让foods成为最后一个元素，先删除之
			array_pop($orderList[$key]);	// food
			array_pop($orderList[$key]);	// 备注
			array_pop($orderList[$key]);	// 电话
			array_pop($orderList[$key]);	// 地址
			array_pop($orderList[$key]);	// 折扣价
			
			$orderList[$key]['total'] = $orderFoodsAndTotal['total'] - 200 + $orderList[$key]['discount_money'];
			$orderList[$key]['discount_money'] 	= $dis_money;
			$orderList[$key]['address']			= $address;
			$orderList[$key]['tell']			= $tell;
			$orderList[$key]['mark']			= $mark;
			$orderList[$key]['foods'] 			= $orderFoodsAndTotal['foods'];
			
		}
		//\Think\Log::write("orderList => " . dump($orderList, false));
		// 对菜篮子号排序
		$newOrderList = $this->getSortedOrderList($orderList);
	    // 设置表头
	    $key = ord("A");
	    foreach($headArr as $v){
		    $colum = chr($key);
		    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum.'1', $v);
		    $key +=1;
	    }
	    
	    $column = 2;
	    $objActSheet = $objPHPExcel->getActiveSheet();
	    
	    // 设置单元格宽度
	    $objActSheet->getColumnDimension('A')->setWidth(15);
	    $objActSheet->getColumnDimension('B')->setWidth(12);
	    $objActSheet->getColumnDimension('C')->setWidth(12);
	    $objActSheet->getColumnDimension('D')->setWidth(12);
	    $objActSheet->getColumnDimension('E')->setWidth(12);
	    $objActSheet->getColumnDimension('F')->setWidth(40);
		$objActSheet->getColumnDimension('G')->setWidth(12);
		$objActSheet->getColumnDimension('H')->setwidth(8);
		$objActSheet->getColumnDimension('I')->setWidth(8);
		$objActSheet->getColumnDimension('J')->setWidth(12);
	    
	    /*$objPHPExcel->getActiveSheet()->getStyle('A')
	    	->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
	    */
	    foreach($newOrderList as $key => $rows) {
		    $span = ord("A");
		    foreach($rows as $keyName => $value) {
			    $j = chr($span);
			    if($keyName == 'basketid'){
				    $objActSheet->setCellValue($j.$column, $value);
				    // 设置单元样式
				    $curColumn = $objActSheet->getStyle("$j$column");
				    $curColumn->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
				    $span++;
				} elseif($keyName == 'autoorder') {
				    if($value == 0) {
					   	$tvalue = '手工订单'; 
				    } elseif($value == 1) {
					    $tvalue = '自动订单';
				    } elseif($value == 2) {
					 	$tvalue = '取消订单';   
				    }
					$objActSheet->setCellValue($j.$column, $tvalue);
					$span++;
               	} elseif($keyName == 'foods') {
					for($i=0;$i<count($value);$i++) {
						$foodName = $value[$i]['foodname'];
						$foodNum = $value[$i]['num'];
						$index = 0;
						foreach($this->curFoodsNames as $fname) {
							if($foodName == '鸡蛋' || $foodName == '土鸡') {
								if($foodName == '鸡蛋') {
									$objActSheet->setCellValue(chr(ord("D")).$column, $foodName.'*'.$foodNum);
								}elseif($foodName == '土鸡') {
									$objActSheet->setCellValue(chr(ord("E")).$column, $foodName.'*'.$foodNum);
								}
								
							}else {
								if($fname == $foodName) {
									$objActSheet->setCellValue(chr($span+$index).$column, $foodName.'*'.$foodNum);
								} else {
									$index++;
								}
							}
							
						}
					}
			    }
			    /*	20180116 将鸡蛋和土鸡放到姓名之后，当循环到truename，将span+3，跳过鸡蛋 土鸡	*/ 
			    elseif($keyName == 'truename') {
				    $objActSheet->setCellValue($j.$column, $value);
					$span+=3;
			    } else {
					$objActSheet->setCellValue($j.$column, $value);
					$span++;
			    }
		    }
		    $column++;
	    }
	    
	    // 删除相关用户隐私列
	    $objActSheet->removeColumn('I')->removeColumn('H')->removeColumn('C');
	    
	    /* ------------ */
	    // 对相关单元格进行合并 | 统计 等操作
	    //$objActSheet->mergeCells('B2:B3');
	    /* ------------ */
	    $fileName = iconv("utf-8", "gb2312", $fileName);
	    
	    $objPHPExcel->setActiveSheetIndex(0);
	    ob_end_clean();
	    header('Content-Type: application/vnd.ms-excel');
	    header("Content-Disposition: attachment;filename=\"$fileName\"");
	    header('Cache-Control: max-age=0');
	    
	    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	    $objWriter->save('php://output');
	    exit;
    }
    
    public function curFoodCountList() {
	    import("Org.Util.PHPExcel");
	    import("Org.Util.PHPExcel.Writer.Excel5");
	    import("Org.Util.PHPExcel.IOFactory");
	    
	    $rand = rand(10,100);
	    $date = date("Y-m-d H:i:s", time());
	    $fileName = "{$date}_$rand.xls";
	    
	    // 设置PHPExcel对象，注意不能少了\
	    $objPHPExcel = new \PHPExcel();
	    $objProps = $objPHPExcel->getProperties();
	    
	    $headArr = array('菜品名', '数量');
	    
	    if($this->curPeriod) {
			$period = $this->curPeriod['periodid'];
		} else {
			// 查询出刚关闭的一期
			$condition_1['doGeneral'] = array('eq', 1);
			$condition_1['status'] = array('eq', 3);
			$lastPeriod = M('period')->where($condition_1)->order('endtime desc')->select();
	        $period = $lastPeriod[0]['periodid'];
		}
	    
	    $condition_1 = array('opid' => $period);
	    $orderList = M('order')->field('tp_order.oid as id, tp_order.basketid as bid, tp_order.ofoods as foods')->where($condition_1)->select();
	    \Think\Log::write("订单数量 = " . count($orderList));
	    /*$data = array(
	    	array('id' => '123', 'name' => '王小二', 'tel' => '12323424'),
	    	array('id' => '345', 'name' => '李三', 'tel' => '434242'),
	    	array('id' => '456', 'name' => '张四', 'tel' => '34535'),
	    );*/

		$countFoods = array();
		for($i=0;$i<count($orderList);$i++) {
			$userFoods = unserialize($orderList[$i]['foods']);
			foreach($userFoods as $key1 => $foods) {
				foreach($foods as $key2 => $food) {
					if(empty($countFoods[$key2])) {
						$countFoods[$key2] = array("name" => $food['name'], "count" => $food['num']);
					} else {
						$num = $countFoods[$key2]['count'] + $food['num'];
						$countFoods[$key2]['count'] = $num;
					}
				}
			}
		}
		
	    // 设置表头
	    $key = ord("A");
	    foreach($headArr as $v){
		    $colum = chr($key);
		    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum.'1', $v);
		    $key +=1;
	    }
	    
	    $column = 2;
	    $objActSheet = $objPHPExcel->getActiveSheet();
	    
	    // 设置单元格宽度
	    $objActSheet->getColumnDimension('A')->setWidth(18);
	    $objActSheet->getColumnDimension('B')->setWidth(6);
	    
	    foreach($countFoods as $key => $rows) {
		    $span = ord("A");
		    foreach($rows as $keyName => $value) {
			    $j = chr($span);
			    $objActSheet->setCellValue($j.$column, $value);
			    $span++;
		    }
		    $column++;
	    }
	    
	    /* ------------ */
	    // 对相关单元格进行合并 | 统计 等操作
	    //$objActSheet->mergeCells('B2:B3');
	    /* ------------ */
	    $fileName = iconv("utf-8", "gb2312", $fileName);
	    
	    $objPHPExcel->setActiveSheetIndex(0);
	    ob_end_clean();
	    header('Content-Type: application/vnd.ms-excel');
	    header("Content-Disposition: attachment;filename=\"$fileName\"");
	    header('Cache-Control: max-age=0');
	    
	    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	    $objWriter->save('php://output');
	    exit;
    }
    
    private function getFoodInfo($orderInfo) {
	    $order = unserialize($orderInfo);
	    $count = 0;
	    $tcount = 0;
	    $thisfood = array();
	    $total = 0;
	    foreach($order as $cfood) {
			$tcount++;
			$count = 0;
			foreach($cfood as $key => $food) {
				$count++;
				$isnew = true;
				$isnew_index = 0;
				for($i=0; $i<count($thisfood); $i++) {
					if ($food['name'] == $thisfood[$i]['foodname']) {
						$isnew = false;
						$isnew_index = $i;
					}
				}
				if($isnew) {
					$thisfood[] = array('foodname' => $food['name'], 'num' => $food['num']);
				} else {
					$newNum = $thisfood[$isnew_index]['num'] + $food['num'];
					$thisfood[$isnew_index]['num'] = $newNum;
					
				}
				$afood = M('food')->where(array('id' => $key))->find();
				$total += $afood['price'] * $food['num'];
			}
	    }
	    $total = floor($total);
		$arr = array();
		$arr['foods']  = $thisfood;
		$arr['total']  = $total;
		return $arr;
    }
    
    private function getFoodInfoStr($orderInfo) {
	    $order = unserialize($orderInfo);
	    $str = '';
	    $count = 0;
	    $tcount = 0;
	    $total = 0;
	    foreach($order as $cfood) {
			$tcount++;
			$count = 0;
			foreach($cfood as $key => $food) {
				$count++;
				$str .= $food['name'].'*'.$food['num'];
				
				$afood = M('food')->where(array('id' => $key))->find();
				$total += $afood['price'] * $food['num'];
				if($count != count($cfood) || $tcount != count($order)) {
					$str .= '|';
				}
			}
	    }
	    $total = floor($total);
		$arr = array();
		$arr['str']  = $str;
		$arr['total'] = $total;
		return $arr;
    }
    
    private function getOpenidList() {
	    $weObj = new \Org\Util\Wechat();
	    $userList = $weObj->getUserList();
	    $openids = $userList['data']['openid'];
	    
	    foreach($openids as $openid) {
			$user_model = M("wxuser");
	        $where = array('openid' => $openid);
	        $userinfo = $user_model->where($where)->find();
	        if($userinfo == null) {
            	$wxuserinfo = $weObj->getUserInfo($openid);
            	/*
            	if($wxuserinfo) {
	            	$newUser = array(
						'openid'			=> $wxuserinfo['openid'],
						'nickname'			=> $wxuserinfo['nickname'],
						'city'				=> $wxuserinfo['city'],
						'province'			=> $wxuserinfo['province'],
						'headimgurl'		=> $wxuserinfo['headimgurl'],
						'subscribe_time'	=> time(),
						'status'			=> 1,	// 订阅状态
					);
					$result = M('wxuser')->add($newUser);
					if($result == true) {
						\Think\Log::write("成功插入", 'INFO');
					} else {
						\Think\Log::write("失败插入", 'INFO');
					}
            	}
            	*/
            }
	    }
    }
    
    private function addUserByOpenid() {
	    $weObj = new \Org\Util\Wechat();
	    $openid = 'oW_r_tnr10kKpa_QDqY18-4KFGYg';
	    $wxuserinfo = $weObj->getUserInfo($openid);
	    
	    $openid = 'oW_r_tmSn7UC_cuP_W5soiJqM8ko';
	    $wxuserinfo = $weObj->getUserInfo($openid);
	    exit;
	    if($wxuserinfo) {
        	$newUser = array(
				'openid'			=> $wxuserinfo['openid'],
				'nickname'			=> $wxuserinfo['nickname'],
				'city'				=> $wxuserinfo['city'],
				'province'			=> $wxuserinfo['province'],
				'headimgurl'		=> $wxuserinfo['headimgurl'],
				'subscribe_time'	=> time(),
				'status'			=> 1,	// 订阅状态
			);
			$result = M('wxuser')->add($newUser);
    	}
    }
    
    public function addCollocationPage() {
	    if(IS_POST) {
		    // 插入到这期套餐表和套餐菜品表中
		    $cid = I('cid');
		    $pid = I('pid');	// 期数id
		    $data1 = array();
		    $data1['coltotalcredit'] = I('tCredit');	// 套餐总分值
		    $data1['colmoney'] = I('tMoney');
		    $data1['createtime'] = time();
		    
		    if(empty($cid)) {
		    	$data1['colname'] = I('cname');
			    $res = M('period_collocation')->add($data1);
			    
			    if($res) {
				    $this->success('套餐添加成功!', U('Admin/Order/showCollocation'), 3);
			    }else {
					    $this->error('套餐添加失败!');
				    }
		    } else {
			    $res = M('period_collocation')->where(array('pcolid' => $cid))->save($data1);
			    if($res) {
			    	$this->success('套餐添加成功!', U('Admin/Order/showCollocation'), 5);
			    }else {
				    $this->error('套餐添加失败!');
			    }
		    }
	    } else {
	    	// 获取当前正在进行的期数
	    	$cid = I('cid');
	    	// 套餐ID不为空
	    	if(!empty($cid)) {
		    	$this->assign('cid', $cid);
				$colinfo = M('period_collocation')->where(array('pcolid' => $cid))->find();
				$this->assign('colname', $colinfo['colname']);
				$this->assign('colcredit', $colinfo['coltotalcredit']);
				// 套餐总价
				$this->assign('colmoney', $colinfo['colmoney']);
	    	} else {
		    	// 查出所有的当前已有的套餐，让其不显示
	    	}
	        
		    $this->display();
	    }
    }
    
    // 获取某一页的菜品列表
    public function getFoodsPage() {
    	header("Content-type: text/html; charset=utf-8");
    	$page = I('page');
    	
    	$food_m = M("food");
    	$count = M('food')->count();    //计算总数
        $Page = new \Think\PageAjax($count, 10);  
        $Page->show();
        
    	$cid = I('cid');
    	// 套餐ID不为空
    	if(!empty($cid)) {
    		$condition_1 = array('pcolid' => $cid);
	    	$cFoods = M('period_collocation_item')->join('__PERIOD_COLLOCATION__ ON __PERIOD_COLLOCATION_ITEM__.PC_COLID = __PERIOD_COLLOCATION__.PCOLID')->where($condition_1)->getField('tp_period_collocation_item.foodid as foodid,tp_period_collocation_item.foodname as name, tp_period_collocation_item.foodid as foodid, tp_period_collocation_item.defchoose as defchs, tp_period_collocation_item.reqchoose as reqchs, tp_period_collocation_item.cicredit as credit, tp_period_collocation_item.price as price');
	    	$this->assign('ofoods', $cFoods);
    	} 
	    $foods =  $food_m->field('tp_food.id as foodid, tp_food.name as name, tp_food.credit as credit, tp_food.price as price')->limit($Page->firstRow.','.$Page->listRows)->select();
	   
        $this->assign('foods', $foods);
	    $this->assign('page', $page);
	    $this->display();
    }
    
    // 获取对应的页码
	public function getFoodsPageHTML() {
		$count = I('count');
		$Page = new \Think\PageAjax($count, 10); 
		$pageContent = $Page->show();
        echo $pageContent;
	}
	
	// 获取当期所有有被点过菜的菜品名称
	private function getCurFoodsNames($orderList) {
		//for($i=0;$i<count($orderList);$i++) {
		foreach($orderList as $key => $order){
			$orderFoods = unserialize($order['foods']);
			foreach($orderFoods as $cfood) {
				foreach($cfood as $key1 => $food) {
					$afoodname = $food['name'];
					$flag_eq = false;
					foreach($this->curFoodsNames as $foodname) {
						if($afoodname == $foodname) {
							$flag_eq = true;
							break;
						}	
					}
					if(!$flag_eq) {
						$this->curFoodsNames[] = $afoodname;
					}
				}
		    }
		}
		// 有对报表的排序进行指定，查看Admin/config.php
		$xls_new_sort = C('xls_new_sort');
		if(!empty($xls_new_sort)) {
			foreach($xls_new_sort as $key => $val) {
				for($i=0; $i<count($this->curFoodsNames); $i++) {
					if($this->curFoodsNames[$i] == $key) {
						$tmpFoodName = $this->curFoodsNames[$val];
						$this->curFoodsNames[$val] = $key;
						$this->curFoodsNames[$i] = $tmpFoodName; 
					}
				}
			}
		}
	}
	
	private function getSortedOrderList($orderList) {
		$orderKeys = array_keys($orderList);
		$newSortList = array();
		foreach($orderKeys as $k) {
			$tmp = $k;
			$v = ''.$k;
			$pos = strpos($v, '-');
			if($pos !== FALSE) {
				$floatNum = strstr($v, '-');
				$floatNum = trim($floatNum, '-');
				$v = substr_replace($v,".",$pos) . $floatNum;
			}
			$v = (float)$v;
			$newSortList[$tmp] = $v;
		}
		asort($newSortList);
		$newOrderList = array();
		foreach($newSortList as $key => $sort) {
			$newOrderList[$key] = $orderList[$key];
		}
		return $newOrderList;
	}
	
}

?>
